import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Button,
  Tag,
  Progress,
  Space,
  Typography,
  Modal,
  Form,
  Input,
  message,
  Tooltip,
  Badge,
  Divider,
  List,
  Select,
} from 'antd';
import {
  HeartOutlined,
  EyeOutlined,
  CloseOutlined,
  UserOutlined,
  EnvironmentOutlined,
  BookOutlined,
  BankOutlined,
  StarOutlined,
  SendOutlined,
  FilterOutlined,
} from '@ant-design/icons';
import { matchAPI } from '@/services/api';
import { MatchRecord } from '@/types';
import { getAvatarUrl } from '@/utils';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

interface PendingMatch {
  id: string;
  userA: {
    id: string;
    nickname: string;
    avatar?: string;
    age: number;
    gender: 'male' | 'female';
    city: string;
    education: string;
    occupation: string;
    tags: string[];
  };
  userB: {
    id: string;
    nickname: string;
    avatar?: string;
    age: number;
    gender: 'male' | 'female';
    city: string;
    education: string;
    occupation: string;
    tags: string[];
  };
  matchScore: number;
  matchReason: string;
  commonInterests: string[];
  distance: number; // km
  recommendedBy: string;
  priority: 'high' | 'medium' | 'low';
}

const MatchList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [pendingMatches, setPendingMatches] = useState<PendingMatch[]>([]);
  const [matchModalVisible, setMatchModalVisible] = useState(false);
  const [selectedMatch, setSelectedMatch] = useState<PendingMatch | null>(null);
  const [form] = Form.useForm();
  const [filters, setFilters] = useState({
    minScore: 70,
    priority: 'all',
    city: 'all',
  });

  // Mock data for pending matches
  const mockPendingMatches: PendingMatch[] = [
    {
      id: '1',
      userA: {
        id: '1',
        nickname: '李小花',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female1',
        age: 26,
        gender: 'female',
        city: '北京',
        education: '本科',
        occupation: '设计师',
        tags: ['旅行', '摄影', '美食'],
      },
      userB: {
        id: '2',
        nickname: '王明',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male1',
        age: 28,
        gender: 'male',
        city: '北京',
        education: '硕士',
        occupation: '工程师',
        tags: ['旅行', '运动', '电影'],
      },
      matchScore: 92,
      matchReason: '兴趣爱好相似，年龄匹配度高',
      commonInterests: ['旅行'],
      distance: 5.2,
      recommendedBy: '智能算法',
      priority: 'high',
    },
    {
      id: '2',
      userA: {
        id: '3',
        nickname: '张丽',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female2',
        age: 24,
        gender: 'female',
        city: '上海',
        education: '本科',
        occupation: '教师',
        tags: ['读书', '音乐', '健身'],
      },
      userB: {
        id: '4',
        nickname: '陈志强',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male2',
        age: 30,
        gender: 'male',
        city: '上海',
        education: '硕士',
        occupation: '医生',
        tags: ['健身', '音乐', '科技'],
      },
      matchScore: 85,
      matchReason: '教育背景相当，地理位置接近',
      commonInterests: ['音乐', '健身'],
      distance: 8.7,
      recommendedBy: '系统推荐',
      priority: 'medium',
    },
    {
      id: '3',
      userA: {
        id: '5',
        nickname: '刘芳',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female3',
        age: 29,
        gender: 'female',
        city: '深圳',
        education: '硕士',
        occupation: '产品经理',
        tags: ['科技', '创业', '瑜伽'],
      },
      userB: {
        id: '6',
        nickname: '赵华',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male3',
        age: 32,
        gender: 'male',
        city: '深圳',
        education: '硕士',
        occupation: '创业者',
        tags: ['创业', '投资', '跑步'],
      },
      matchScore: 78,
      matchReason: '职业互补，价值观契合',
      commonInterests: ['创业'],
      distance: 3.1,
      recommendedBy: '人工推荐',
      priority: 'medium',
    },
  ];

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return '#ff4d4f';
      case 'medium': return '#fa8c16';
      case 'low': return '#52c41a';
      default: return '#d9d9d9';
    }
  };

  const getScoreColor = (score: number) => {
    if (score >= 90) return '#52c41a';
    if (score >= 80) return '#fa8c16';
    if (score >= 70) return '#1890ff';
    return '#ff4d4f';
  };

  const handleMatch = (match: PendingMatch) => {
    setSelectedMatch(match);
    form.setFieldsValue({
      userAId: match.userA.id,
      userBId: match.userB.id,
      recommendation: `基于智能算法分析，${match.userA.nickname}和${match.userB.nickname}在${match.commonInterests.join('、')}等方面高度契合，匹配度达到${match.matchScore}%。建议进行牵线尝试。`,
    });
    setMatchModalVisible(true);
  };

  const handleSubmitMatch = async (values: any) => {
    try {
      setLoading(true);
      
      // Call match API
      // await matchAPI.createMatch(values);
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success('牵线请求已发送');
      setMatchModalVisible(false);
      form.resetFields();
      
      // Remove from pending list
      setPendingMatches(prev => prev.filter(m => m.id !== selectedMatch?.id));
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSkip = (matchId: string) => {
    Modal.confirm({
      title: '确定跳过此匹配？',
      content: '跳过后该匹配将加入冷名单，30天内不再推荐',
      onOk: () => {
        setPendingMatches(prev => prev.filter(m => m.id !== matchId));
        message.success('已跳过此匹配');
      },
    });
  };

  const loadPendingMatches = async () => {
    try {
      setLoading(true);
      // const response = await matchAPI.getMatchList({ page: 1, pageSize: 20 });
      // if (response.success) {
      //   setPendingMatches(response.data.list);
      // }
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 500));
      setPendingMatches(mockPendingMatches);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const filteredMatches = pendingMatches.filter(match => {
    if (match.matchScore < filters.minScore) return false;
    if (filters.priority !== 'all' && match.priority !== filters.priority) return false;
    if (filters.city !== 'all' && match.userA.city !== filters.city && match.userB.city !== filters.city) return false;
    return true;
  });

  useEffect(() => {
    loadPendingMatches();
  }, []);

  return (
    <div className="page-container">
      <div className="page-header">
        <Title level={4} className="page-title">待牵线列表</Title>
        <Text className="page-description">
          基于智能算法推荐的高质量匹配对象，支持人工干预和个性化推荐
        </Text>
      </div>

      {/* Filter Section */}
      <Card style={{ marginBottom: '16px' }} bodyStyle={{ paddingBottom: '0' }}>
        <Row gutter={[16, 16]} align="middle">
          <Col xs={24} sm={8} md={4}>
            <Space>
              <FilterOutlined />
              <Text strong>筛选条件：</Text>
            </Space>
          </Col>
          <Col xs={24} sm={8} md={5}>
            <Space>
              <Text>最低匹配分：</Text>
              <Select
                value={filters.minScore}
                onChange={(value) => setFilters({ ...filters, minScore: value })}
                style={{ width: 100 }}
              >
                <Select.Option value={60}>60分</Select.Option>
                <Select.Option value={70}>70分</Select.Option>
                <Select.Option value={80}>80分</Select.Option>
                <Select.Option value={90}>90分</Select.Option>
              </Select>
            </Space>
          </Col>
          <Col xs={24} sm={8} md={4}>
            <Space>
              <Text>优先级：</Text>
              <Select
                value={filters.priority}
                onChange={(value) => setFilters({ ...filters, priority: value })}
                style={{ width: 100 }}
              >
                <Select.Option value="all">全部</Select.Option>
                <Select.Option value="high">高</Select.Option>
                <Select.Option value="medium">中</Select.Option>
                <Select.Option value="low">低</Select.Option>
              </Select>
            </Space>
          </Col>
          <Col xs={24} sm={24} md={6}>
            <Space>
              <Text type="secondary">共找到 {filteredMatches.length} 个匹配</Text>
              <Button onClick={loadPendingMatches} loading={loading}>
                刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* Match Cards */}
      <Row gutter={[16, 16]}>
        {filteredMatches.map((match) => (
          <Col xs={24} lg={12} key={match.id}>
            <Card
              hoverable
              style={{ position: 'relative' }}
              bodyStyle={{ padding: '20px' }}
            >
              {/* Priority Badge */}
              <Badge.Ribbon
                text={`${match.priority === 'high' ? '高' : match.priority === 'medium' ? '中' : '低'}优先级`}
                color={getPriorityColor(match.priority)}
              >
                <div>
                  {/* Match Score */}
                  <div style={{ textAlign: 'center', marginBottom: '16px' }}>
                    <Progress
                      type="circle"
                      percent={match.matchScore}
                      size={60}
                      strokeColor={getScoreColor(match.matchScore)}
                      format={(percent) => (
                        <span style={{ fontSize: '12px', fontWeight: 'bold' }}>
                          {percent}%
                        </span>
                      )}
                    />
                    <div style={{ marginTop: '4px' }}>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        匹配度
                      </Text>
                    </div>
                  </div>

                  {/* Users Info */}
                  <Row gutter={[16, 16]} align="middle">
                    <Col span={10}>
                      <div style={{ textAlign: 'center' }}>
                        <Avatar
                          size={64}
                          src={getAvatarUrl(match.userA.avatar, match.userA.gender)}
                          icon={<UserOutlined />}
                        />
                        <div style={{ marginTop: '8px' }}>
                          <Text strong>{match.userA.nickname}</Text>
                          <br />
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            {match.userA.age}岁 • {match.userA.gender === 'male' ? '男' : '女'}
                          </Text>
                          <br />
                          <Space size={4} style={{ marginTop: '4px' }}>
                            <EnvironmentOutlined style={{ fontSize: '10px' }} />
                            <Text type="secondary" style={{ fontSize: '10px' }}>
                              {match.userA.city}
                            </Text>
                          </Space>
                          <br />
                          <Space size={4}>
                            <BookOutlined style={{ fontSize: '10px' }} />
                            <Text type="secondary" style={{ fontSize: '10px' }}>
                              {match.userA.education}
                            </Text>
                          </Space>
                          <br />
                          <Space size={4}>
                            <BankOutlined style={{ fontSize: '10px' }} />
                            <Text type="secondary" style={{ fontSize: '10px' }}>
                              {match.userA.occupation}
                            </Text>
                          </Space>
                        </div>
                      </div>
                    </Col>
                    
                    <Col span={4}>
                      <div style={{ textAlign: 'center' }}>
                        <HeartOutlined style={{ fontSize: '24px', color: '#eb2f96' }} />
                        <div style={{ marginTop: '8px' }}>
                          <Text type="secondary" style={{ fontSize: '10px' }}>
                            距离 {match.distance}km
                          </Text>
                        </div>
                      </div>
                    </Col>
                    
                    <Col span={10}>
                      <div style={{ textAlign: 'center' }}>
                        <Avatar
                          size={64}
                          src={getAvatarUrl(match.userB.avatar, match.userB.gender)}
                          icon={<UserOutlined />}
                        />
                        <div style={{ marginTop: '8px' }}>
                          <Text strong>{match.userB.nickname}</Text>
                          <br />
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            {match.userB.age}岁 • {match.userB.gender === 'male' ? '男' : '女'}
                          </Text>
                          <br />
                          <Space size={4} style={{ marginTop: '4px' }}>
                            <EnvironmentOutlined style={{ fontSize: '10px' }} />
                            <Text type="secondary" style={{ fontSize: '10px' }}>
                              {match.userB.city}
                            </Text>
                          </Space>
                          <br />
                          <Space size={4}>
                            <BookOutlined style={{ fontSize: '10px' }} />
                            <Text type="secondary" style={{ fontSize: '10px' }}>
                              {match.userB.education}
                            </Text>
                          </Space>
                          <br />
                          <Space size={4}>
                            <BankOutlined style={{ fontSize: '10px' }} />
                            <Text type="secondary" style={{ fontSize: '10px' }}>
                              {match.userB.occupation}
                            </Text>
                          </Space>
                        </div>
                      </div>
                    </Col>
                  </Row>

                  <Divider style={{ margin: '16px 0' }} />

                  {/* Match Details */}
                  <div>
                    <div style={{ marginBottom: '8px' }}>
                      <Text strong style={{ fontSize: '12px' }}>推荐理由：</Text>
                      <Text style={{ fontSize: '12px' }}>{match.matchReason}</Text>
                    </div>
                    
                    <div style={{ marginBottom: '12px' }}>
                      <Text strong style={{ fontSize: '12px' }}>共同兴趣：</Text>
                      <div style={{ marginTop: '4px' }}>
                        {match.commonInterests.map((interest, index) => (
                          <Tag key={index} size="small" color="blue">{interest}</Tag>
                        ))}
                      </div>
                    </div>
                    
                    <div style={{ marginBottom: '12px' }}>
                      <Text type="secondary" style={{ fontSize: '11px' }}>
                        <StarOutlined /> 推荐来源：{match.recommendedBy}
                      </Text>
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div style={{ textAlign: 'center' }}>
                    <Space>
                      <Tooltip title="查看详细资料">
                        <Button size="small" icon={<EyeOutlined />}>
                          查看详情
                        </Button>
                      </Tooltip>
                      <Button
                        type="primary"
                        size="small"
                        icon={<SendOutlined />}
                        onClick={() => handleMatch(match)}
                      >
                        立即牵线
                      </Button>
                      <Tooltip title="暂不匹配">
                        <Button
                          size="small"
                          icon={<CloseOutlined />}
                          onClick={() => handleSkip(match.id)}
                        >
                          跳过
                        </Button>
                      </Tooltip>
                    </Space>
                  </div>
                </div>
              </Badge.Ribbon>
            </Card>
          </Col>
        ))}
      </Row>

      {filteredMatches.length === 0 && !loading && (
        <Card>
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <HeartOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }} />
            <div>
              <Text type="secondary">暂无符合条件的匹配推荐</Text>
            </div>
          </div>
        </Card>
      )}

      {/* Match Modal */}
      <Modal
        title="确认牵线操作"
        open={matchModalVisible}
        onCancel={() => setMatchModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedMatch && (
          <div>
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <Space size={24}>
                <div>
                  <Avatar
                    size={64}
                    src={getAvatarUrl(selectedMatch.userA.avatar, selectedMatch.userA.gender)}
                    icon={<UserOutlined />}
                  />
                  <div style={{ marginTop: '8px' }}>
                    <Text strong>{selectedMatch.userA.nickname}</Text>
                  </div>
                </div>
                <HeartOutlined style={{ fontSize: '32px', color: '#eb2f96', marginTop: '16px' }} />
                <div>
                  <Avatar
                    size={64}
                    src={getAvatarUrl(selectedMatch.userB.avatar, selectedMatch.userB.gender)}
                    icon={<UserOutlined />}
                  />
                  <div style={{ marginTop: '8px' }}>
                    <Text strong>{selectedMatch.userB.nickname}</Text>
                  </div>
                </div>
              </Space>
            </div>

            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmitMatch}
            >
              <Form.Item name="userAId" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="userBId" hidden>
                <Input />
              </Form.Item>
              
              <Form.Item
                label="推荐语"
                name="recommendation"
                rules={[{ required: true, message: '请输入推荐语' }]}
              >
                <TextArea
                  rows={4}
                  placeholder="请输入个性化推荐语，将发送给双方用户"
                />
              </Form.Item>
              
              <Form.Item
                label="备注说明"
                name="notes"
              >
                <TextArea
                  rows={2}
                  placeholder="内部备注（用户不可见）"
                />
              </Form.Item>
              
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    确认牵线
                  </Button>
                  <Button onClick={() => setMatchModalVisible(false)}>
                    取消
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default MatchList;